<template>
  <div class="cityList" ref="wrapper">
    <div>
      <div class="row list-bg pl-3">
        <div class="col">当前城市</div>
      </div>
      <div class="row m-0">
        <!-- <div class="list-box">{{this.$store.state.city}}</div> -->
        <!-- step1:利用mapState -->
        <div class="list-box">{{this.curCity}}</div>
      </div>
      <!-- hot city -->
      <div class="row list-bg pl-3">
        <div class="col">热门城市</div>
      </div>
      <div class="row m-0">
        <div
          class="list-box"
          v-for="item of hotCity"
          :key="item.id"
          @click="changeCity(item.name)"
        >{{item.name}}</div>
      </div>
      <!-- all cities -->
      <div class="row" v-for="(value, key) in allCity" :key="key">
        <div class="col my-2">
          <div class="list-bg pl-3" :ref="key">{{key}}</div>
          <ul class="p-0">
            <li
              v-for="item in value"
              :key="item.id"
              class="border-bottom bg-light w-100 py-1 pl-3"
              @click="changeCity(item.name)"
            >{{item.name}}</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from "better-scroll";
// step2:引入
import { mapState, mapMutations } from "vuex";
export default {
  name: "CityList",
  props: {
    hotCity: {
      type: Array,
      required: true
    },
    allCity: {
      type: Object,
      required: true
    },
    char: {
      type: String,
      required: true
    }
  },
  data() {
    return {};
  },
  components: {},
  methods: {
    changeCity(city) {
      // 可忽略Actions, 直接使用commit;
      // this.$store.dispatch("change", city);
      // this.$store.commit("changeState", city);
      // 如果采用mapMutations
      this.changeState(city);
      this.$router.push("/");
    },
    ...mapMutations(["changeState"])
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.wrapper, {
      click: true,
      mouseWheel: true
    });
  },
  activated() {
    this.scroll.scrollTo(0, 0);
  },
  watch: {
    char() {
      if (this.char) {
        // console.log(this.$refs[this.char]);
        this.scroll.scrollToElement(this.$refs[this.char][0]);
      }
    }
  },
  computed: {
    // step3:计算mapState
    ...mapState({
      curCity: "city"
    })
  }
};
</script>


<style scoped>
.cityList {
  position: absolute;
  top: 4.8rem;
  left: 0;
  right: 0;
  bottom: 0;
  /* background: #f40; */
  overflow: hidden;
  /* 手机端一般没有鼠标滑动 */
  /* overflow-y: scroll; */
}
.list-bg {
  background: #ccc;
  padding: 0.2rem;
}
.list-box {
  border: 1px solid #ccc;
  width: 25%;
  margin-left: 1rem;
  text-align: center;
  margin: 0.4rem;
  /* background: #f40; */
}
</style>
